package cn.b.sky.form.service.impl;

import cn.b.sky.common.model.BatchJobReport;
import cn.b.sky.common.model.Page;
import cn.b.sky.common.utils.DatabaseUtils;
import cn.b.sky.i18n.utils.LocaleResourceBundle;
import cn.b.sky.form.dao.BusinessFieldDao;
import cn.b.sky.form.dao.BusinessFieldValueDao;
import cn.b.sky.form.model.BusinessField;
import cn.b.sky.form.model.BusinessFieldValue;
import cn.b.sky.form.model.condition.BusinessFieldCondition;
import cn.b.sky.form.model.condition.BusinessFieldValueCondition;
import cn.b.sky.form.service.BusinessFieldService;
import cn.b.sky.user.SecurityContextUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * 
 * <strong>Title : BusinessFieldServiceImpl.java<br></strong>
 * <strong>Package : cn.b.sky.flowable.service.impl<br></strong>
 * <strong>Description : </strong>业务字段操作业务类实现<br> 
 * <strong>Create on : 2016-09-27 下午07:18:57<br></strong>
 * <p>
 * @author JunLin.Yang<br>
 * @version <strong>v1.0.0</strong>
 */
@Service("businessFieldService")
public class BusinessFieldServiceImpl implements BusinessFieldService {

  private static final Logger LOGGER = LoggerFactory.getLogger(BusinessFieldServiceImpl.class);

  @Resource
  private BusinessFieldDao businessFieldDao;

  @Resource
  private BusinessFieldValueDao businessFieldValueDao;

  @Override
  public int insertBusinessField(BusinessField data) {
    if (null == data) {
      return 0;
    }
    data.preProcessingToStore();
    return this.businessFieldDao.insertBusinessField(data);
  }

  @Override
  public int updateBusinessField(BusinessField data) {
    if (null == data) {
      return 0;
    }
    data.preProcessingToStore();
    return this.businessFieldDao.updateBusinessField(data);
  }

  @Override
  public BatchJobReport deleteBusinessField(BusinessField data) {
    if (null == data) {
      return new BatchJobReport("", "data is null", false);
    }
    return this.deleteBusinessFieldByPrimaryKey(data.getBusinessType(), data.getSiteCode(), data.getBusinessField());
  }

  @Override
  public long getBusinessFieldsCount() {
    return this.businessFieldDao.getBusinessFieldsCount();
  }

  @Override
  public List<BusinessField> selectBusinessFields(String siteCode, String businessType) {
    return this.businessFieldDao.selectBusinessFields(siteCode, businessType);
  }

  @Override
  public BatchJobReport deleteBusinessFieldByPrimaryKey(String siteCode, String businessType, String businessField) {
    String cause = "";
    Boolean success = false;
    try {
      BusinessFieldValueCondition businessFieldValueCondition = new BusinessFieldValueCondition();
      businessFieldValueCondition.setSiteCode(siteCode);
      businessFieldValueCondition.setBusinessType(businessType);
      businessFieldValueCondition.setBusinessField(businessField);
      this.businessFieldValueDao.deleteBusinessFieldValueByCondition(businessFieldValueCondition);
      this.businessFieldDao.deleteBusinessFieldByPrimaryKey(siteCode, businessType, businessField);
      success = true;
    } catch (Exception e) {
      LOGGER.error("{}", e);
      TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
      if (DatabaseUtils.isConstraintsError(e.getMessage())) {
        // 外键删除已存在提示
        cause = LocaleResourceBundle.getCommonResourceLabel(SecurityContextUtil.getSiteCode(),
            SecurityContextUtil.getLanguageCode(), "dataBaseOperationPkFail.M")
            + LocaleResourceBundle.getCommonResourceLabel(SecurityContextUtil.getSiteCode(),
                SecurityContextUtil.getLanguageCode(), "notDelete.M");
      } else {
        cause = e.getMessage();
      }
      success = false;
    }
    return new BatchJobReport(businessField, cause, success);
  }

  @Override
  public BusinessField getBusinessFieldByPrimaryKey(String siteCode, String businessType, String businessField) {
    return this.businessFieldDao.getBusinessFieldByPrimaryKey(siteCode, businessType, businessField);
  }

  @Override
  public boolean existBusinessFieldByPrimaryKey(String siteCode, String businessType, String businessField) {
    return this.businessFieldDao.existBusinessFieldByPrimaryKey(siteCode, businessType, businessField);
  }

  @Override
  public boolean existsBusinessFieldByCondition(BusinessFieldCondition condition) {
    return this.businessFieldDao.existsBusinessFieldByCondition(condition);
  }

  @Override
  public BusinessField getBusinessFieldByCondition(BusinessFieldCondition condition) {
    return this.businessFieldDao.getBusinessFieldByCondition(condition);
  }

  @Override
  public List<BusinessField> selectBusinessFieldsByCondition(BusinessFieldCondition condition) {
    return this.businessFieldDao.selectBusinessFieldsByCondition(condition);
  }

  @Override
  public List<BusinessField> selectBusinessFieldPageDataByCondition(BusinessFieldCondition condition) {
    return this.businessFieldDao.selectBusinessFieldPageDataByCondition(condition);
  }

  @Override
  public Page selectBusinessFieldPageByCondition(BusinessFieldCondition condition) {
    condition.setData(this.businessFieldDao.selectBusinessFieldPageDataByCondition(condition));
    condition.setTotalCount(this.businessFieldDao.getBusinessFieldsCountByCondition(condition));
    return condition;
  }

  @Override
  public long getBusinessFieldsCountByCondition(BusinessFieldCondition condition) {
    return this.businessFieldDao.getBusinessFieldsCountByCondition(condition);
  }

  @Override
  public int insertBusinessFieldAndValues(BusinessField data) {
    if (null == data) {
      return 0;
    }
    data.preProcessingToStore();
    //针对静态和动态选项值进行处理
    if(!"DYNAMICOPTION".equalsIgnoreCase(data.getDataType())){
      data.setQuerySql(null);
    }
    if(!"STATICOPTION".equalsIgnoreCase(data.getDataType())){
      data.setBusinessFieldValueList(null);
    }
    
    int n = this.businessFieldDao.insertBusinessField(data);
    if (!CollectionUtils.isEmpty(data.getBusinessFieldValueList())) {
      for (BusinessFieldValue businessFieldValue : data.getBusinessFieldValueList()) {
        if (null != businessFieldValue && StringUtils.isNotBlank(businessFieldValue.getValue())) {
          businessFieldValue.setSiteCode(data.getSiteCode());
          businessFieldValue.setBusinessField(data.getBusinessField());
          businessFieldValue.setBusinessType(data.getBusinessType());
          this.businessFieldValueDao.insertBusinessFieldValue(businessFieldValue);
        }
      }
    }

    return n;
  }

  @Override
  public int updateBusinessFieldAndValues(BusinessField data) {
    if (null == data) {
      return 0;
    }
    data.preProcessingToStore();
    //针对静态和动态选项值进行处理
    if(!"DYNAMICOPTION".equalsIgnoreCase(data.getDataType())){
      data.setQuerySql(null);
    }
    if(!"STATICOPTION".equalsIgnoreCase(data.getDataType())){
      data.setBusinessFieldValueList(null);
    }
    
    int n = this.businessFieldDao.updateBusinessField(data);
    BusinessFieldValueCondition businessFieldValueCondition = new BusinessFieldValueCondition();
    businessFieldValueCondition.setBusinessType(data.getBusinessType());
    businessFieldValueCondition.setBusinessField(data.getBusinessField());
    businessFieldValueCondition.setSiteCode(data.getSiteCode());

    //删除对应字段下的值列表信息
    this.businessFieldValueDao.deleteBusinessFieldValueByCondition(businessFieldValueCondition);

    if (!CollectionUtils.isEmpty(data.getBusinessFieldValueList())) {
      for (BusinessFieldValue businessFieldValue : data.getBusinessFieldValueList()) {
        if (null != businessFieldValue  && StringUtils.isNotBlank(businessFieldValue.getValue())) {
          businessFieldValue.setSiteCode(data.getSiteCode());
          businessFieldValue.setBusinessField(data.getBusinessField());
          businessFieldValue.setBusinessType(data.getBusinessType());
          this.businessFieldValueDao.insertBusinessFieldValue(businessFieldValue);
        }
      }
    }

    return n;
  }

  @Override
  public BusinessField getBusinessFieldAndValues(String siteCode, String businessType, String businessField) {
    BusinessField businessFieldData = this.businessFieldDao.getBusinessFieldByPrimaryKey(siteCode, businessType,
        businessField);
    if (null != businessFieldData) {
      BusinessFieldValueCondition businessFieldValueCondition = new BusinessFieldValueCondition();
      businessFieldValueCondition.setBusinessType(businessType);
      businessFieldValueCondition.setBusinessField(businessField);
      businessFieldValueCondition.setSiteCode(siteCode);
      businessFieldData.setBusinessFieldValueList(
          this.businessFieldValueDao.selectBusinessFieldValuesByCondition(businessFieldValueCondition));
    }
    return businessFieldData;
  }

  @Override
  public List<BusinessField> getOnBusinessField(BusinessFieldCondition condition) {
    return businessFieldDao.getOnBusinessField(condition);
  }

  @Override
  public int getOnBusinessFieldCount(BusinessFieldCondition condition) {
    return businessFieldDao.getOnBusinessFieldCount(condition);
  }

  @Override
  public BusinessFieldValue getBusinessFieldValueByPrimaryKey(String siteCode, String businessType,
      String businessField, String value) {
    return businessFieldValueDao.getBusinessFieldValueByPrimaryKey(siteCode, businessType, businessField, value);
  }
}
